var superagent = require('superagent')
var cherrio = require('cheerio')
var async = require('async')
var url = 'http://www.xicidaili.com/nn/'

// eslint-disable-next-line camelcase
function get_ip_list (callback) {
  superagent.get(url)
    .set('User-Agent', 'Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/535.1 (KHTML, like Gecko) Chrome/14.0.835.163 Safari/535.1')
    .set('Cache-Control', 'max-age=0')
    .set('Connection', 'keep-alive')
    .end(function (err, res) {
      if (err) {
        console.log('proxy' + err)
      }

      let $ = cherrio.load(res.text)
      let ipArr = []
      for (let i = 1; i < $('#ip_list tbody tr').length; i++) {
        let ip = 'http://' + $('#ip_list tbody tr').eq(i).find('td').eq(1).html() + ':' + $('#ip_list tbody tr').eq(i).find('td').eq(2).html()
        ipArr.push(ip)
      }

      callback(null, ipArr)
    })
}

// eslint-disable-next-line camelcase
function get_random_ip (arg1, callback) {
  var position = Math.round(Math.random() * 100)
  callback(null, arg1[position])
}

// eslint-disable-next-line camelcase
function return_proxy () {
  // eslint-disable-next-line camelcase
  async.waterfall([get_ip_list, get_random_ip], function (err, result) {
    if (err) {
      console.log(err)
    }

    return result
  })
}

module.exports = return_proxy()
